package com.example.module.flipper;


import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.animation.AccelerateInterpolator;

public class Flip3d {
	public static final int FLIP_DURATION = 1000; 
	private Activity activity;
	private View prevView, nextView;
	private OnLoadScreenshotListener onLoadScreenshotListener;
	private FlipAction flipAction;
	
	public interface OnLoadScreenshotListener {
		public void onLoadScreenshot();
	}

	public Flip3d(Activity activity, View prevView, View nextView, FlipAction flipAction) {
		this.activity = activity;
		this.prevView = prevView;
		this.nextView = nextView;
		this.flipAction = flipAction;
	}
	
	public void rotateView() {
		if (flipAction == FlipAction.FLIP_FORWARD)
			applyRotation(0, 90);
		else
			applyRotation(0, -90);
		
		flipAction = FlipAction.DONE;
	}

	public void applyRotation(float start, float end) {
		// Find the center of image
		Display disp = activity.getWindowManager().getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		disp.getMetrics(metrics);
		
		boolean isForward = (flipAction == FlipAction.FLIP_FORWARD);
		final float centerX = disp.getWidth() / 2.0f;
		final float centerY = disp.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Flip3dAnimation rotation = new Flip3dAnimation(start, end, centerX, centerY);
		rotation.setDuration(FLIP_DURATION);
		rotation.setFillAfter(false);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(isForward, prevView, nextView));
		
		prevView.setVisibility(View.VISIBLE);
		nextView.setVisibility(View.GONE);
		prevView.requestFocus();

		prevView.startAnimation(rotation);
	}

	public OnLoadScreenshotListener getOnLoadScreenshotListener() {
		return onLoadScreenshotListener;
	}

	public void setOnLoadScreenshotListener(OnLoadScreenshotListener onLoadScreenshotListener) {
		this.onLoadScreenshotListener = onLoadScreenshotListener;
	}

	public FlipAction getFlipAction() {
		return flipAction;
	}

	public void setFlipAction(FlipAction flipAction) {
		this.flipAction = flipAction;
	}
}
